import { Bot } from "./Bot.js";
import mineflayer from "mineflayer";
import { ConsoleColor } from "../utils/consoleColor.js";
import { getStatePrompt } from "../utils/get/getState.js";

function handleStatus(bot: mineflayer.Bot, wrapperBot: Bot): void {
  DebugCommand.bothPrint(`当前状态: ${getStatePrompt(bot)}`);
  DebugCommand.bothPrint("已输出到终端", bot);
}

function handleClear(bot: mineflayer.Bot, wrapperBot: Bot): void {
  DebugCommand.bothPrint("清除对话历史", bot);
  wrapperBot._content.clearContents();
}

function handleSummary(bot: mineflayer.Bot, wrapperBot: Bot): void {
  const summary = wrapperBot._content.getSummary();
  DebugCommand.bothPrint(`对话总结: ${summary}`, bot);
}

function handleReload(bot: mineflayer.Bot, wrapperBot: Bot): void {
  DebugCommand.bothPrint("重新加载配置", bot);
  wrapperBot.start();
}

function handleHelp(bot: mineflayer.Bot) {
  DebugCommand.bothPrint("可用调试命令:", bot);
  Object.entries(COMMAND_DESCRIPTIONS).map(([cmd, desc]) => {
    DebugCommand.bothPrint(`${cmd}: ${desc}`, bot);
  });
}

function handleActList(bot: mineflayer.Bot, wrapperBot: Bot) {
  DebugCommand.bothPrint(wrapperBot._actManager.getActDoc());
  DebugCommand.bothPrint("已输出到终端", bot);
}

const COMMAND_DESCRIPTIONS: Record<string, string> = {
  status: "显示机器人当前状态到终端",
  clear: "清除对话历史",
  summary: "输出当前对话的总结",
  reload: "重新加载配置并重启",
  help: "显示此帮助信息",
  actlist: "显示当前可用的行动列表到终端",
};

const COMMAND_HANDLERS: Record<string, (bot: mineflayer.Bot, wrapperBot: Bot) => void> = {
  status: (bot, wrapperBot) => handleStatus(bot, wrapperBot),
  clear: (bot, wrapperBot) => handleClear(bot, wrapperBot),
  summary: (bot, wrapperBot) => handleSummary(bot, wrapperBot),
  reload: (bot, wrapperBot) => handleReload(bot, wrapperBot),
  help: (bot) => handleHelp(bot),
  actlist: (bot, wrapperBot) => handleActList(bot, wrapperBot),
};

export class DebugCommand {
  static chatModeMap = new Map<string, string>();
  static userNameSet = new Set<string>();

  static bothPrint(str: string, bot?: mineflayer.Bot) {
    console.log(ConsoleColor.blue(`[DebugCommand] ${str}`));
    if (bot) {
      if (this.chatModeMap.get(bot.username) === "chat") bot.chat?.(`[DebugCommand] ${str}`);
      else {
        for (const name of this.userNameSet) {
          bot.whisper?.(name, `[DebugCommand] ${str}`);
        }
      }
    }
  }

  static processCommand(bot: Bot, command: string, chatMode = "chat", userName?: string): void {
    const handler = COMMAND_HANDLERS[command];
    if (userName) this.userNameSet.add(userName);
    this.chatModeMap.set(bot._botName, chatMode);
    if (handler) {
      handler(bot._bot, bot);
    } else {
      this.bothPrint(`未知命令: ${command}`, bot._bot);
    }
  }
}
